package cn.xinfei.xdecision.manager.web.aop;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.xinfei.xdecision.common.model.common.ResponseEntityDto;
import cn.xinfei.xdecision.common.model.login.AccountSessionWrap;
import cn.xinfei.xdecision.common.model.login.SessionManager;
import cn.xinfei.xdecision.common.model.monitor.logger.OperateLog;
import cn.xinfei.xdecision.common.model.monitor.logger.dto.OperateLogCreateDTO;
import cn.xinfei.xdecision.common.service.monitor.logger.impl.OperateLogServiceImpl;
import cn.xinfei.xdecision.common.utils.constant.OperateTypeEnum;
import cn.xinfei.xdecision.common.utils.util.JsonUtils;
import cn.xinfei.xdecision.common.utils.util.StringUtil;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.IntStream;

import static cn.xinfei.xdecision.common.utils.exception.enums.ErrorCodeEnum.SERVER_ERROR;
import static cn.xinfei.xdecision.common.utils.exception.enums.ErrorCodeEnum.SUCCESS;

/**
 * 拦截添加 @ArchivesLog 注解的请求，记录操作日志
 */
@Aspect
@Component
@Order(2)
@Slf4j
public class ArchivesLogAspect {
    @Resource
    private OperateLogServiceImpl operateLogService;

    /**
     * @param
     * @return HttpServletRequest
     * @Description: 获取request
     */
    public HttpServletRequest getHttpServletRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }


    @Around("@annotation(archivesLog)")
    public Object around(ProceedingJoinPoint joinPoint, ArchivesLog archivesLog) throws Throwable {
        LocalDateTime startTime = LocalDateTime.now();

        try {

            Object result = joinPoint.proceed();
            this.log(joinPoint, archivesLog, startTime, result, null);
            return result;
        } catch (Throwable exception) {
            this.log(joinPoint, archivesLog, startTime, null, exception);
            throw exception;
        }
    }

    private void log(ProceedingJoinPoint joinPoint, ArchivesLog archivesLog, LocalDateTime startTime, Object result, Throwable exception) {
        try {
            OperateLog operateLog = new OperateLog();

            //补全通用字段
            AccountSessionWrap session = SessionManager.getSession();
            String traceId = session.getTraceId();
            operateLog.setTraceId(traceId);
            operateLog.setStartTime(startTime);

            fillUserFields(operateLog);

            fillModuleFields(operateLog, joinPoint, archivesLog);

            fillRequestFields(operateLog);

            fillMethodFields(operateLog, joinPoint, archivesLog, startTime, result, exception);

            OperateLogCreateDTO createDTO = new OperateLogCreateDTO();
            BeanUtils.copyProperties(operateLog, createDTO);
            createDTO.setOrganId(SessionManager.getLoginAccount().getOrganId());
            operateLogService.createOperateLog(createDTO);
        } catch (Throwable ex) {
            log.error("记录操作日志时，发生异常。joinPoint({}) operateLog({}) apiOperation({}) result({}) exception({})", joinPoint, archivesLog, result, exception, ex);
        }
    }

    private void fillUserFields(OperateLog operateLog) {
        operateLog.setUserId(SessionManager.getLoginUserId());
    }

    private void fillModuleFields(OperateLog operateLog, ProceedingJoinPoint joinPoint, ArchivesLog archivesLog) {
        if (archivesLog != null) {
            operateLog.setModule(archivesLog.module());
        }

        if (StringUtil.isBlank(operateLog.getModule())) {
            Api api = getClassAnnotation(joinPoint, Api.class);
            if (api != null) {

                if (StringUtil.isValidStr(api.value())) {
                    operateLog.setModule(api.value());
                }
                if (StringUtil.isBlank(operateLog.getModule()) && ArrayUtil.isNotEmpty(api.tags())) {
                    operateLog.setModule(api.tags()[0]);
                }
            }
        }

        if (archivesLog != null) {
            operateLog.setName(archivesLog.name());
        }

        if (archivesLog != null && ArrayUtil.isNotEmpty(archivesLog.type())) {
            operateLog.setType(archivesLog.type()[0].getType());
        }
        if (operateLog.getType() == null) {
            RequestMethod requestMethod = obtainFirstMatchRequestMethod(obtainRequestMethod(joinPoint));
            OperateTypeEnum operateLogType = convertOperateLogType(requestMethod);
            operateLog.setType(operateLogType != null ? operateLogType.getType() : null);
        }
    }

    private OperateTypeEnum convertOperateLogType(RequestMethod requestMethod) {
        if (requestMethod == null) {
            return null;
        }
        switch (requestMethod) {
            case GET:
                return OperateTypeEnum.GET;
            case POST:
                return OperateTypeEnum.CREATE;
            case PUT:
                return OperateTypeEnum.UPDATE;
            case DELETE:
                return OperateTypeEnum.DELETE;
            default:
                return OperateTypeEnum.OTHER;
        }
    }

    private void fillRequestFields(OperateLog operateLogObj) {
        // 获得 Request 对象
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) {
            return;
        }
        // 补全请求信息
        operateLogObj.setRequestMethod(request.getMethod());
        operateLogObj.setRequestUrl(request.getRequestURI());
        operateLogObj.setUserIp(ServletUtil.getClientIP(request));
    }

    private static void fillMethodFields(OperateLog operateLogObj,
                                         ProceedingJoinPoint joinPoint,
                                         ArchivesLog archivesLog,
                                         LocalDateTime startTime, Object result, Throwable exception) {
        if (archivesLog == null || archivesLog.logArgs()) {
            operateLogObj.setJavaMethodArgs(obtainMethodArgs(joinPoint));
        }
        if (archivesLog == null || archivesLog.logResultData()) {
            operateLogObj.setResultData(obtainResultData(result));
        }
        operateLogObj.setDuration((int) (LocalDateTimeUtil.between(startTime, LocalDateTime.now()).toMillis()));
        // （正常）处理 resultCode 和 resultMsg 字段
        if (result instanceof ResponseEntityDto) {
            ResponseEntityDto<?> commonResult = (ResponseEntityDto<?>) result;
            operateLogObj.setResultCode(commonResult.getError());
            operateLogObj.setResultMsg(commonResult.getMsg());
        } else {
            operateLogObj.setResultCode(SUCCESS.getCode());
        }
        // （异常）处理 resultCode 和 resultMsg 字段
        if (exception != null) {
            operateLogObj.setResultCode(SERVER_ERROR.getCode());
            operateLogObj.setResultMsg(ExceptionUtil.getRootCauseMessage(exception));
        }
    }

    private static String obtainMethodArgs(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] argNames = methodSignature.getParameterNames();
        Object[] argValues = joinPoint.getArgs();
        // 拼接参数
        Map<String, Object> args = Maps.newHashMapWithExpectedSize(argValues.length);
        for (int i = 0; i < argNames.length; i++) {
            String argName = argNames[i];
            Object argValue = argValues[i];
            // 被忽略时，标记为 ignore 字符串，避免和 null 混在一起
            args.put(argName, !isIgnoreArgs(argValue) ? argValue : "[ignore]");
        }
        return JsonUtils.toJsonString(args);
    }

    private static String obtainResultData(Object result) {
        if (Objects.isNull(result)) {
            return null;
        }
        if (result instanceof ResponseEntityDto) {
            result = ((ResponseEntityDto<?>) result).getData();
        }
        return JsonUtils.toJsonString(result);
    }

    private static boolean isIgnoreArgs(Object object) {
        Class<?> clazz = object.getClass();
        // 处理数组的情况
        if (clazz.isArray()) {
            return IntStream.range(0, Array.getLength(object))
                    .anyMatch(index -> isIgnoreArgs(Array.get(object, index)));
        }
        // 递归，处理数组、Collection、Map 的情况
        if (Collection.class.isAssignableFrom(clazz)) {
            return ((Collection<?>) object).stream()
                    .anyMatch((Predicate<Object>) ArchivesLogAspect::isIgnoreArgs);
        }
        if (Map.class.isAssignableFrom(clazz)) {
            return isIgnoreArgs(((Map<?, ?>) object).values());
        }
        // obj
        return object instanceof MultipartFile
                || object instanceof HttpServletRequest
                || object instanceof HttpServletResponse
                || object instanceof BindingResult;
    }

    private static <T extends Annotation> T getClassAnnotation(ProceedingJoinPoint joinPoint, Class<T> annotationClass) {
        return ((MethodSignature) joinPoint.getSignature()).getMethod().getDeclaringClass().getAnnotation(annotationClass);
    }

    private static RequestMethod[] obtainRequestMethod(ProceedingJoinPoint joinPoint) {
        RequestMapping requestMapping = AnnotationUtils.getAnnotation( // 使用 Spring 的工具类，可以处理 @RequestMapping 别名注解
                ((MethodSignature) joinPoint.getSignature()).getMethod(), RequestMapping.class);
        return requestMapping != null ? requestMapping.method() : new RequestMethod[]{};
    }

    private static RequestMethod obtainFirstMatchRequestMethod(RequestMethod[] requestMethods) {
        if (ArrayUtil.isEmpty(requestMethods)) {
            return null;
        }
        // 优先，匹配最优的 POST、PUT、DELETE
        RequestMethod result = obtainFirstLogRequestMethod(requestMethods);
        if (result != null) {
            return result;
        }
        // 然后，匹配次优的 GET
        result = Arrays.stream(requestMethods).filter(requestMethod -> requestMethod == RequestMethod.GET)
                .findFirst().orElse(null);
        if (result != null) {
            return result;
        }
        // 兜底，获得第一个
        return requestMethods[0];
    }

    private static RequestMethod obtainFirstLogRequestMethod(RequestMethod[] requestMethods) {
        if (ArrayUtil.isEmpty(requestMethods)) {
            return null;
        }
        return Arrays.stream(requestMethods).filter(requestMethod ->
                requestMethod == RequestMethod.POST
                        || requestMethod == RequestMethod.PUT
                        || requestMethod == RequestMethod.DELETE)
                .findFirst().orElse(null);
    }
}
